package com.zwr.sheller.customer.Service.Impl;

import com.zwr.sheller.core.common.BusinessException;
import com.zwr.sheller.core.common.WDMBusinessException;
import com.zwr.sheller.core.common.WDMExceptionCode;
import com.zwr.sheller.core.pojo.Order;
import com.zwr.sheller.core.pojo.OriginOrder;
import com.zwr.sheller.core.pojo.Sku;
import com.zwr.sheller.core.pojo.SnowFlake;
import com.zwr.sheller.core.service.impl.BaseServiceImpl;
import com.zwr.sheller.core.util.JsonUtil;
import com.zwr.sheller.customer.Service.OrderService;
import com.zwr.sheller.customer.config.RabbitConfig;
import com.zwr.sheller.customer.mapper.OriginOrderMapper;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service("orderService")
public class OrderServiceImpl extends BaseServiceImpl<OriginOrder> implements OrderService {


    @Autowired(required = false)
    private OriginOrderMapper orderMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public final static String SALES_VOLUME = "salesVolume:";
@Override
    public OriginOrder createOrder(Map<String ,Object> maps) throws WDMBusinessException, BusinessException {
     /*   Map<String,Integer> skuIdWithNumber = (Map<String,Integer>) maps.get("skuIdWithNumber");
        Set<Map.Entry<String, Integer>> entries = skuIdWithNumber.entrySet();
        //削减库存
        for (Map.Entry<String, Integer> entry : entries) {
            Sku skuFromRedis =(Sku) redisTemplate.opsForValue().get(ShoppingCartServiceImpl.SKU_ID + entry.getKey());

            while (skuFromRedis.getSkuStock()<entry.getValue()){
                throw  new WDMBusinessException(WDMExceptionCode.SKU_OUT_OF_STOCK);
            }
             //判断销量缓存是否存在
            if (redisTemplate.hasKey("salesVolume:")){
                redisTemplate.opsForZSet().incrementScore("salesVolume:",skuFromRedis.getGoodsId(),entry.getValue());
            }else {
                redisTemplate.expire("salesVolume:",24*30,TimeUnit.HOURS);
                redisTemplate.opsForZSet().add("salesVolume:",skuFromRedis.getGoodsId(),entry.getValue());
            }

            //直接删除对应的sku缓存
            redisTemplate.delete(ShoppingCartServiceImpl.SKU_ID+entry.getKey());

        }*/
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        maps.put("orderPromotionMethod",4);
        maps.put("orderDiscountedPrice",0);
        maps.put("orderCreateTime", timestamp);
        maps.put("orderDayTime",timestamp.toString().substring(0,9));
        long orderNum = SnowFlake.nextId();
        maps.put("orderNum", orderNum);

    //生成订单对象
    OriginOrder order = new OriginOrder();
    order.setOrderNum(maps.get("orderNum").toString());
    order.setOrderDeliveryMethod(Long.valueOf(maps.get("orderDeliveryMethod").toString()));
    order.setOrderWithBill(Boolean.valueOf(maps.get("orderWithBill").toString()));
    order.setOrderBillType(Integer.valueOf(maps.get("orderBillType").toString()));
    order.setOrderBillInvoice(Integer.valueOf(maps.get("orderBillInvoice").toString()));
    order.setOrderVerificationCode(maps.get("orderVerificationCode").toString());
    order.setOrderPromotionMethod(Integer.valueOf(maps.get("orderPromotionMethod").toString()));
    order.setOrderDiscountedPrice(Double.valueOf(maps.get("orderDiscountedPrice").toString()));
    order.setOrderWayPay(Integer.valueOf(maps.get("orderWayPay").toString()));
    order.setOrderDayTime(maps.get("orderDayTime").toString());
    order.setOrderCreateTime(Timestamp.valueOf(maps.get("orderCreateTime").toString()));
    order.setOrderRemark(maps.get("orderRemark").toString());
    order.setOrderStatus(1);
    order.setShopId(Long.valueOf(maps.get("shopId").toString()));
    order.setAddressId(Long.valueOf(maps.get("addressId").toString()));
    order.setUserId(Long.valueOf(maps.get("userId").toString()));
    order.setOranizationName(maps.get("oranizationName").toString());
    order.setInvoiceContent(Integer.valueOf(maps.get("invoiceContent").toString()));
    order.setTaxpayerIdentificationNumber(maps.get("taxpayerIdentificationNumber").toString());



    Map<String,Object> map = new HashMap<>();

    map.put("order",order);
    map.put("skuIdWithNumber",maps.get("skuIdWithNumber"));

    System.out.println(map);

        //将订单详细订单信息发送到 -> 前后端交互队列
        rabbitTemplate.convertAndSend(RabbitConfig.INTERACTIVE_EXCHANGE,RabbitConfig.INTERACTIVE_ROUTING_KEY,JsonUtil.objectToString(map));
        //将订单编号发送到死信部分的真正队列，并设置过期时间
        rabbitTemplate.convertAndSend(RabbitConfig.ORDER_EXCHANGE,RabbitConfig.ORDER_ROUTING_KEY,JsonUtil.objectToString(orderNum),messagePostProcessor());

        return order;
    }

    @Override
    public void updateOrderField(OriginOrder order) {
        Example example = new Example(OriginOrder.class);
        Example.Criteria orderNum = example.createCriteria().andEqualTo("orderNum", order.getOrderNum());

        orderMapper.updateByExampleSelective(order,example);
    }


    //发送消息的处理方法，添加过期时间
    private MessagePostProcessor messagePostProcessor(){
        return new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置有效期30分钟
                //测试10秒后过期
                message.getMessageProperties().setExpiration("10000");
                return message;
            }
        };
    }
}
